package com.livestocksolutions.intent;

import java.util.ArrayList;

import com.livestocksolutions.Business;
import com.livestocksolutions.ContactAddress;
import com.livestocksolutions.ContactDetail;
import com.livestocksolutions.ContactPhone;
import com.livestocksolutions.Farm;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.Owner;
import com.livestocksolutions.R;
import com.livestocksolutions.ui.ListContactArrayAdapter;
import com.livestocksolutions.ui.ViewOwnerArrayAdapter;
import com.livestocksolutions.util.StringArrayParcelable;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

/* -- Version History --
 *  1.0 : 02 August 2012 - Initial version.
 *  
 *  1.1 : 13 August 2012 - Created super class BaseActivity to hold all methods that are
 *                         standard across Activities
 *                         
 *  1.2 : 08 September 2012 - Changed underlying structure to avoid using ListView for 
 *                         listed items that can be modifiable so that everything behaves
 *                         on screen rotation and upon the display of the virtual keyboard.
 */

/**
 * This class manages a Owner object
 * @author Adam Parr
 * @version 1.2
 * 
 * @.modified 16 September 2012
 */
public class OwnerActivity extends BaseActivity {
	public static final int BUSINESSVIEW 		 	= 0;
	/**
	 * Stores the reference to the XML layout template for each view
	 * @see #BUSINESSVIEW
	 */
	public static final Integer[] RESOURCEID = new Integer[]{
		R.layout.item
	};
	
	/**
	 * Owner View that holds the data of the Owner
	 */
	private ViewOwnerArrayAdapter ownerView;
	/**
	 * Contact View that holds the contact list data of the Owner
	 */
	private ListContactArrayAdapter contacts;
	
	/**
	 * Constructor
	 */
	public OwnerActivity() {
		super(RESOURCEID);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if(stack.size()==0){
        	setContentView(RESOURCEID[BUSINESSVIEW]);
        	if(!built){
        		// If Owner ever becomes viewable only remove the following line.
        		edit=true;
    			// Put the ID of this Owner Object
    			id = id!=-1?id:getIntent().getExtras().getLong(ITEMID,-1);
    			Owner o = LivestockSolutions.getOwnerByID(id);
    			// Read initial state of the Owner Object and add to ownerType and contactValues
    			String[] ownerType = new String[ViewOwnerArrayAdapter.SIZE];
    			String[][] contactValues = new String[][]{};
    			ContactAddress ca=null;
    			if(o!=null){
	    			ownerType[ViewOwnerArrayAdapter.ID] 				= String.valueOf(o.getID());
	    			ownerType[ViewOwnerArrayAdapter.NAME] 				= o.getName();
	    			
	    			if(o instanceof Business || o instanceof Farm){
	    				ca = ((Business)o).getAddress();
	    				ownerType[ViewOwnerArrayAdapter.STREETADDRESS]	= ca.getStreet();
	    	            ownerType[ViewOwnerArrayAdapter.TOWNADDRESS] 	= ca.getTown();
	    	            ownerType[ViewOwnerArrayAdapter.POSTCODEADDRESS]= String.valueOf(ca.getPostcode());
	
						if(o instanceof Farm){
							ownerType[ViewOwnerArrayAdapter.FARMPIC] 	= ((Farm) o).getFarmID();
							ownerType[ViewOwnerArrayAdapter.TYPE]		= String.valueOf(ViewOwnerArrayAdapter.TYPE_FARM);
						}else{
							ownerType[ViewOwnerArrayAdapter.TYPE]		= String.valueOf(ViewOwnerArrayAdapter.TYPE_BUSINESS);
						}
	    			}else{
	    				 ownerType[ViewOwnerArrayAdapter.TYPE]			= String.valueOf(ViewOwnerArrayAdapter.TYPE_OTHER);
	    			}
    			
		            ContactDetail[] contactDetailList = o.getContacts();
		            ArrayList<String[]> contactTempValues = new ArrayList<String[]>();
		            for(int x=0; x<contactDetailList.length; x++){
		            	if(contactDetailList[x]!=ca){
			            	String[] item = new String[ListContactArrayAdapter.SIZE];
			            	
			            	String[] array = getResources().getStringArray(R.array.contact_type);
			            	for(int y=0; y < array.length; y++){
			        			if(contactDetailList[x].getType()==null || array[y].toLowerCase().equals(contactDetailList[x].getType().toLowerCase())){
			        				item[ListContactArrayAdapter.TYPE]=String.valueOf(y);
			        				break;
			        			}
			        		}
			            	
			            	if(contactDetailList[x] instanceof ContactAddress){
			            		item[ListContactArrayAdapter.STREETADDRESS]=((ContactAddress)contactDetailList[x]).getStreet();
			            		item[ListContactArrayAdapter.TOWNADDRESS]=((ContactAddress)contactDetailList[x]).getTown();
				            	item[ListContactArrayAdapter.POSTCODEADDRESS]=String.valueOf(((ContactAddress)contactDetailList[x]).getPostcode());
				    			
			            	}else{
			            		item[ListContactArrayAdapter.STREETADDRESS]=contactDetailList[x].getValue();
			            	}
			            	contactTempValues.add(item);
		            	}
		            }
		            contactValues = contactTempValues.toArray(new String[][]{});
    			}
				
				ownerView = new ViewOwnerArrayAdapter(this, ownerType);
		    	contacts = new ListContactArrayAdapter(this, contactValues);
		    	setPage();
		    	drawContacts();
	            
				currentState.putInt(STATEID,BUSINESSVIEW);
	    		built = true;
    		}
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Show the menu for an Owner Object
        getMenuInflater().inflate(R.menu.owner_menu, menu);
        this.menu=menu;
        return true;
    }
    
    @Override
    public void onBackPressed() {
    	edit=false;
    	super.onBackPressed();
    	edit=true;
    }

    
    @Override
    public void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState (outState);
    	
    	outState.putParcelable("ownerView", new StringArrayParcelable().setStrings(ownerView.get()));
    	outState.putParcelable("ownerContact", new StringArrayParcelable().setStrings(contacts.get()));
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState) {
    	ownerView = new ViewOwnerArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("ownerView")).getStrings()[0]);
    	contacts = new ListContactArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("ownerContact")).getStrings());

    	super.onRestoreInstanceState (inState);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    	int position = view.getId();
    	final String[] contactarray = getResources().getStringArray(R.array.contact_type);
    	if(position>=0 && position<contacts.getCount()){
	    	String[] strArray = contacts.getItem(position);
	    	if(strArray.length>0){
	    		setSelected(view);
		    	String s = contactarray[Integer.parseInt(strArray[0])] + ": ";
		    	int length = strArray[0].equals(getResources().getStringArray(R.array.contact_type)[ListContactArrayAdapter.TYPE_ADDRESS])? strArray.length : ListContactArrayAdapter.TOWNADDRESS;
		    	for(int x = 1; x < length; x++){
		    		s+=strArray[x]!=null?strArray[x]+", ":"";
		    	}
		    	s=s.substring(0, s.length()-2);
		    	menu.setHeaderTitle(s);
		        String[] menuItems = getResources().getStringArray(R.array.context_menu_contact);
		        for (int i = 0; i<menuItems.length; i++) {
		        	menu.add(Menu.NONE, i, i, menuItems[i]);
		        }
	    	}
    	}
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	if(getSelected() != null) {
			int position = getSelected().getId();
			setSelected(null);
			int menuItemIndex = item.getItemId();
			String[] menuItems = getResources().getStringArray(R.array.context_menu_contact);
			// IF Delete menu item is selected
			if(menuItems[menuItemIndex].equals(this.getResources().getString(R.string.menu_delete))){
				// Delete the item
				contacts.remove(contacts.getItem(position));
				// Re-draw the list of contact details
				drawContacts();

				return true;
			}
    	}
    	return false;
    }
    
    @Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_add_contact:
        		// Add a blank contact
        		LinearLayout contactView = (LinearLayout) findViewById(R.id.contactView);
        		contacts.add(new String[]{});
        		View v = contacts.getView(contacts.getCount()-1, null, contactView);
            	registerForContextMenu(v);
            	contactView.addView(v,contacts.getCount()-1);
        		break;
        		
        	case R.id.menu_save:
        		if(ownerView.isValid()){
	        		edit = true;
	        		final String[] contactarray = getResources().getStringArray(R.array.contact_type);
	        		
	        		Owner o;
	        		if(Integer.parseInt(ownerView.get()[0][ViewOwnerArrayAdapter.TYPE])==ViewOwnerArrayAdapter.TYPE_BUSINESS || Integer.parseInt(ownerView.get()[0][ViewOwnerArrayAdapter.TYPE])==ViewOwnerArrayAdapter.TYPE_FARM){
	        			if(Integer.parseInt(ownerView.get()[0][ViewOwnerArrayAdapter.TYPE])==ViewOwnerArrayAdapter.TYPE_FARM){
	        				o = id==-1?new Farm():LivestockSolutions.getOwnerByID(id);
	        				o=o.changeType(Farm.class);
	        				((Farm)o).setFarmID(ownerView.get()[0][ViewOwnerArrayAdapter.FARMPIC]);
	        			}else{
	        				o = id==-1?new Business():LivestockSolutions.getOwnerByID(id);
	        				o=o.changeType(Business.class);
	        			}
	        			ContactAddress ca = new ContactAddress();
	        			ca.setStreet(ownerView.get()[0][ViewOwnerArrayAdapter.STREETADDRESS]);
	        			ca.setTown(ownerView.get()[0][ViewOwnerArrayAdapter.TOWNADDRESS]);
	        			ca.setPostcode(Integer.parseInt(ownerView.get()[0][ViewOwnerArrayAdapter.POSTCODEADDRESS]));
	        			ca.setType(contactarray[ListContactArrayAdapter.TYPE_ADDRESS]);
	        			((Business)o).setAddress(ca);
	        		}else{
	        			o = id==-1?new Owner():LivestockSolutions.getOwnerByID(id);
        				o=o.changeType(Owner.class);
	        		}
	        		
	        		// Remove any existing contacts first
	        		for(int x=o.getContacts().length; x>0; x--){
	        			o.removeContact(x-1);
	        		}
	        		String[][] contactList = contacts.get();
	        		for(int x=0; x<contactList.length; x++){
	        			ContactDetail ca = null;
    					if(Integer.parseInt(contactList[x][ListContactArrayAdapter.TYPE])==ListContactArrayAdapter.TYPE_ADDRESS){
    						ca = new ContactAddress();
    						((ContactAddress)ca).setStreet(contactList[x][ListContactArrayAdapter.STREETADDRESS]);
    						((ContactAddress)ca).setTown(contactList[x][ListContactArrayAdapter.TOWNADDRESS]);
    						((ContactAddress)ca).setPostcode(Integer.parseInt(contactList[x][ListContactArrayAdapter.POSTCODEADDRESS]));
    					}else if(Integer.parseInt(contactList[x][ListContactArrayAdapter.TYPE])==ListContactArrayAdapter.TYPE_PHONE || Integer.parseInt(contactList[x][ListContactArrayAdapter.TYPE])==ListContactArrayAdapter.TYPE_FAX){
    						ca = new ContactPhone();
    						((ContactPhone)ca).setNumber(contactList[x][ListContactArrayAdapter.STREETADDRESS]);
    					}else if(Integer.parseInt(contactList[x][ListContactArrayAdapter.TYPE])==ListContactArrayAdapter.TYPE_EMAIL || Integer.parseInt(contactList[x][ListContactArrayAdapter.TYPE])==ListContactArrayAdapter.TYPE_OTHER){
    						ca = new ContactDetail();
    						ca.setValue(contactList[x][ListContactArrayAdapter.STREETADDRESS]);
    					}
    					if(ca!=null){
    						ca.setType(contactarray[Integer.parseInt(contactList[x][ListContactArrayAdapter.TYPE])]);
    					}
    					o.addContact(ca);
	        		}

	        		id=o.getID();
	        		if(LivestockSolutions.addOwner(o)){
	        			Toast.makeText(this,getResources().getString(R.string.message_saved,getResources().getString(R.string.contact)),Toast.LENGTH_SHORT).show();
	        		}else{
	        			Toast.makeText(this,getResources().getString(R.string.message_errorSave,getResources().getString(R.string.contact),getResources().getString(R.string.message_unknown)),Toast.LENGTH_SHORT).show();
	        		}
	        		
	        		built=false;
	        		onPrepareOptionsMenu(menu);
	        		showView(currentState.getInt(STATEID,BUSINESSVIEW),currentState);
	        		// Pop current view
	        		stack.pop();
	        		// Pop edit change (No edit view on this one)
	        		//stack.pop();
	        		break;
        		}
		        //$FALL-THROUGH$
			default:
	        	return super.frameSelection(frame);
        }
        return true;
    }
    
	@Override
	public boolean constructFrame(int view) {
		switch (view) {
			case BUSINESSVIEW:
				setContentView(RESOURCEID[BUSINESSVIEW]);
				setPage();
				drawContacts();
				break;
			default:
				return false;
		}
		return true;
	}
    
    /**
     * Set up the view to show the relevant content
     */
    private void setPage(){
    	LinearLayout itemView = (LinearLayout) findViewById(R.id.listView);
    	// Not Implemented for an Owner
    	if(edit){
    		//ownerView.setModifyOwner();
	    }else{
	    	//ownerView.setViewOwner();
	    }
    	ownerView.setRoot(itemView);
    	itemView.addView(ownerView.getView(0,null, itemView),0);
    }
    
    private void drawContacts(){
    	LinearLayout contactView = (LinearLayout) findViewById(R.id.contactView);
    	contactView.removeAllViews();
    	contacts.setRoot(contactView);
    	for(int x=0; x< contacts.getCount(); x++){
    		View v = contacts.getView(x, null, contactView);
    		registerForContextMenu(v);
    		contactView.addView(v,x);
    	}
    }
}